import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.sql.Time;
import java.util.Date;
import java.util.Random;


public class Cliente implements Runnable{
	Socket socket;
	ObjectOutputStream out;
	ObjectInputStream in;

	public Cliente() {
		try {
			socket = new Socket("127.0.0.1", 9688);
			out = new ObjectOutputStream(socket.getOutputStream());
			in = new ObjectInputStream(socket.getInputStream());
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		Random rand = new Random();
		rand.setSeed(System.currentTimeMillis());
		try {
			out.writeInt(1);
			out.flush();
			out.writeInt(696);
			int ponto=(rand.nextInt(5)+1);
			out.writeInt(ponto); 
			System.out.println(ponto+"");
			Time tempo=new Time(rand.nextInt(24), rand.nextInt(60), rand.nextInt(60));
			out.writeObject(tempo);
			out.flush();
			/*String p=new String("");
			try {
				p = (String) in.readObject();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println(""+p);*/
			System.out.println(tempo.toString());
			int espe=-1;
			try {
				espe = (int)in.readObject();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("tempo esperado: "+espe);
			//out.writeInt(3);
			//out.flush();
			//socket.close();
			Thread.sleep(1000*espe);
			/*tempo.setMinutes(tempo.getMinutes()+(espe%60));
			while(rand.nextInt(100)>70){
				Thread.sleep(1000*espe);
				tempo.setMinutes(tempo.getMinutes()+(espe%60));
			}*/
			/*try {
				socket = new Socket("127.0.0.1", 9688);
				out = new ObjectOutputStream(socket.getOutputStream());
				in = new ObjectInputStream(socket.getInputStream());
			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}*/
			out.writeInt(2);
			out.flush();
			out.writeInt(696);
			out.writeInt(ponto);
			out.writeInt(espe);
			out.writeObject(tempo);
			out.flush();
			try {
				String str= (String)in.readObject();
				System.out.println(str);
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			out.writeInt(3);
			out.flush();
		} catch (IOException | InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
